#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "http_request.h"

#define BUF_LEN 1024

static void setpair(const char *buf, const char *key, char *value);

void log(char *str);

int build_request(struct http_request *request)
{
	char buf[BUF_LEN];
	char *uri, *method;
	char *p;

	memset((char*)request, 0, sizeof(*request));
	fgets(buf, BUF_LEN, stdin);
	

	//method
	method = strtok(buf, " ");
	strcpy(request->method, method);

	uri = strtok(0, " ");
	//file_name
	p = request->file_name;
	while(*uri != '?' && *uri != 0)
		*p++ = *uri++;
	*p = 0;

	//query_string
	if(*uri == '?'){
		uri++;
		request->query_string = malloc(strlen(uri));
		strcpy(request->query_string, uri);
	}

	while(fgets(buf, BUF_LEN, stdin) != NULL){
		if(strcmp(buf, "\r\n") == 0)
			break;
		setpair(buf, "Host", request->host);
		setpair(buf, "Content-Type", request->content_type);
		setpair(buf, "Content-Length", request->content_length);
	}
	
	return 0;
}

int free_request(struct http_request *request)
{
	if(request->query_string != NULL){
		free(request->query_string);
	}

	if(request->content != NULL){
		free(request->content);
	}

	if(request->cookie != NULL){
		free(request->cookie);
	}
	return 0;
}


int header(char *str)
{
	printf("%s\r\n", str);
	return 0;
}


static void setpair(const char *buf, const char *key, char *value)
{
	while(*key){
		if(*buf++ != *key++){
			return;
		}
	}
	strcpy(value, buf + 1);
}

void log(char *str)
{
	fprintf(stderr, "%s\n", str);
}
